package com.archie.xunji.guanzhu;


import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.archie.xunji.R;
import com.archie.xunji.guanzhu.adapters.AttentionAdapter;
import com.archie.xunji.guanzhu.entitys.Attention;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import java.io.IOException;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class AttentionFragment extends Fragment implements AdapterView.OnItemClickListener {

    private AttentionAdapter adapter;
    private ListView listView;
    private List<Attention> attentionData;
    private TextView list_detail_attitude;
    private MediaPlayer mPlay ;
    public AttentionFragment() {
        // Required empty public constructor
    }
    private int nowPosition=-1;
    private int position;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_attention, container, false);
        initView(view);
        initData();

        return view;
    }

    private void initView(View view) {
        listView = (ListView) view.findViewById(R.id.attention_listView);
        list_detail_attitude = (TextView) view.findViewById(R.id.list_detail_attitude);
        listView.setOnItemClickListener(this);
    }


    private void initData() {
        RequestParams params = new RequestParams();
//&imei=9692B6993494E9324B7F9560912242B7&os=Android+4.4.4&key=WANDOUJIA
        params.addBodyParameter("userinfoid", "26099");
        params.addBodyParameter("appuserid", "43480");
        params.addBodyParameter("t", "20151110192240");
        params.addBodyParameter("token", "180DD4DF4E0CD4EB1B839DFE022F07C1D9C7C9DA");
        params.addBodyParameter("sid", "TehvuUT2Ud");
        params.addBodyParameter("imei", "9692B6993494E9324B7F9560912242B7");
        params.addBodyParameter("os", "Android+4.4.4");
        params.addBodyParameter("key", "WANDOUJIA");
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST,
                "http://service.xunjimap.com/xunjiservice/common1_0_4/follow?53D2CFEB65F6BBEEEB42836FE18E7E0D",
                params,
                new RequestCallBack<String>() {
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                        if (isUploading) {
                        } else {
                        }
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                         attentionData = Attention.getAttentionData(responseInfo.result);
                        if (attentionData != null) {
                            adapter = new AttentionAdapter(attentionData,getActivity());
                            listView.setAdapter(adapter);
                            adapter.setOnAttentionChangeListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Object tag = v.getTag();
                                    // 获取 Adapter 中设置的 Tag
                                    if (tag != null && tag instanceof Integer) {
                                        int position = (Integer) tag;
                                        if (!attentionData.get(position).isAttituded()) {
                                            int attitudecount = attentionData.get(position).getAttitudecount() + 1;
                                            attentionData.get(position).setAttitudecount(attitudecount);
                                            attentionData.get(position).setIsAttituded(true);
                                            adapter.notifyDataSetChanged();
                                        }
                                    }
                                }
                            });
                            adapter.setOnFavouriteChangeListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Object tag = v.getTag();
                                    // 获取 Adapter 中设置的 Tag
                                    if (tag != null && tag instanceof Integer) {
                                        int position = (Integer) tag;
                                        if (!attentionData.get(position).isFavourited()) {
                                            attentionData.get(position).setIsFavourited(true);
                                            adapter.notifyDataSetChanged();
                                        }
                                    }
                                }
                            });

                            adapter.setOnMusicPlay(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Object tag = v.getTag();
                                    // 获取 Adapter 中设置的 Tag
                                    if (tag != null && tag instanceof Integer) {
                                        position = (Integer) tag;
                                        if(mPlay!=null&&position==nowPosition) {
                                            Log.i("statueposition","position-->"+position+"nowposition-->"+nowPosition);
                                            if (mPlay.isPlaying())  //如果正在播放，暂停
                                            {
                                                mPlay.pause();
                                                attentionData.get(position).setIsPlaying(false);
                                                int surplusTime = (mPlay.getDuration()-mPlay.getCurrentPosition())/1000;
                                                attentionData.get(position).setSurplusTime(surplusTime+"");
                                                adapter.notifyDataSetChanged();
                                            }else//如果没有播放，开始播放
                                            {
                                                mPlay.start();
                                                attentionData.get(position).setIsPlaying(true);
                                                int surplusTime = (mPlay.getDuration()-mPlay.getCurrentPosition())/1000;
                                                attentionData.get(position).setSurplusTime(surplusTime+"");
                                                adapter.notifyDataSetChanged();
//                                                new Thread(new Runnable() {
//                                                    @Override
//                                                    public void run() {
//                                                        View adapterView = listView.getChildAt(position);
//                                                        try {
//                                                            int surplusTime = (mPlay.getDuration()-mPlay.getCurrentPosition())/1000;
//                                                            Log.i("nowTime","-->"+surplusTime);
//                                                            while(surplusTime>0) {
//                                                                Thread.sleep(200);
//                                                                surplusTime = (mPlay.getDuration() - mPlay.getCurrentPosition()) / 1000;
//                                                                Log.i("nowTime","-->"+surplusTime);
//                                                                TextView t = (TextView) adapterView.findViewById(R.id.list_detail_music_play);
//                                                                t.setText(surplusTime+"");
//                                                            }
//                                                        } catch (InterruptedException e) {
//                                                            e.printStackTrace();
//                                                        }
//                                                    }
//                                                }).start();
                                                //开启计算播放进度的线程
                                            }
                                        }else if(mPlay!=null&&position!=nowPosition){
                                            if (mPlay.isPlaying())
                                            {//停止播放
                                                mPlay.stop();
                                            }
                                            //释放资源
                                            mPlay.release();
                                            attentionData.get(nowPosition).setIsPlaying(false);
                                            nowPosition = position;
                                            mPlay = new MediaPlayer();
                                            mPlay.reset();
                                            try {
                                                mPlay.setDataSource("http://imagecdn.xunjimap.com/image/" + attentionData.get(position).getAudiourl());
                                                mPlay.prepare();
                                                mPlay.start();
                                                attentionData.get(position).setIsPlaying(true);
                                                int surplusTime = (mPlay.getDuration()-mPlay.getCurrentPosition())/1000;
                                                attentionData.get(position).setSurplusTime(surplusTime + "");
                                                adapter.notifyDataSetChanged();

                                            } catch (IOException e) {
                                                e.printStackTrace();
                                            }
                                        }else if(mPlay==null){ //没有播放，即第一次播放
                                            nowPosition = position;
                                            mPlay = new MediaPlayer();
                                            mPlay.reset();
                                            try {
                                                mPlay.setDataSource("http://imagecdn.xunjimap.com/image/" + attentionData.get(position).getAudiourl());
                                                mPlay.prepare();

                                                mPlay.start();
                                                attentionData.get(position).setIsPlaying(true);
                                                int surplusTime = (mPlay.getDuration()-mPlay.getCurrentPosition())/1000;
                                                attentionData.get(position).setSurplusTime(surplusTime+"");
                                                adapter.notifyDataSetChanged();
                                            } catch (IOException e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    }
                                }
                            });

                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Toast.makeText(getActivity(),"数据加载失败！",Toast.LENGTH_SHORT).show();
                    }
                });
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
        //停止播放
        if (mPlay!=null) {
            if(mPlay.isPlaying())
                mPlay.stop();
            //释放资源
            mPlay.release();
            mPlay = null;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent();
        intent.setClass(getActivity(),TopicDetailActivity.class);
        intent.putExtra("attention",attentionData.get(position));
        startActivity(intent);
    }
}
